package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.utils.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.ShopConstant.SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(5);

    @Override
    public Result queryShopById(Long id) {
        // 查询数据
        Shop shop = cacheClient.LogicalExpire(SHOP_KEY, id, Shop.class, this::getById, 30L, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        // 返回数据
        return Result.ok(shop);
    }

    /**
     * 缓存穿透
     * @param id 店铺id
     * @return 商铺信息
     */
    private Shop cachePenetration(Long id) {
        String key = SHOP_KEY + id;
        // 1、从redis中查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            // 2、redis中命中，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 查询到空对象，直接返回店铺信息不存在
        if (shopJson != null) {
            return null;
        }

        // 3、redis中未命中，查询数据库
        Shop shop = getById(id);
        if (shop == null) {
            // 数据库中不存在数据，缓存空对象，2分钟有效期
            stringRedisTemplate.opsForValue().set(key, "", 2L, TimeUnit.MINUTES);
            return null;
        }
        // 4、建立缓存，设置过期时间
        // 为了避免缓存雪崩，给缓存设置随机数（30-40min）
        int randomInt = RandomUtil.randomInt(0, 10);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), 30L + randomInt, TimeUnit.MINUTES);
        return shop;
    }

    /**
     * 缓存击穿之互斥锁
     * @param id
     * @return
     */
    private Shop cacheByMutex(Long id) {
        String shopKey = SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        if (StrUtil.isNotBlank(shopJson)) {
            // 2、redis中命中，直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 查询到空对象，直接返回店铺信息不存在
        if (shopJson != null) {
            return null;
        }
        // 缓存未命中的操作逻辑
        // 1、获取互斥锁
        Shop shop = null;
        String key = "lock:shop:" + id;
        try {
            boolean lock = tryLock(key);
            if (!lock) {
                // 获取锁失败，休眠一段时间
                Thread.sleep(10);
                return cacheByMutex(id);
            }
            // 2、获取锁成功
            // 2.1 先判断缓存是否重建好
            String s = stringRedisTemplate.opsForValue().get(shopKey);
            if (StrUtil.isNotBlank(s)) {
                return JSONUtil.toBean(s, Shop.class);
            }
            if (s != null) {
                return null;
            }
            // 2.2 查询数据库
            shop = getById(id);
            // 2.3 建立缓存
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(shopKey, "", 2L, TimeUnit.MINUTES);
            }
            int randomInt = RandomUtil.randomInt(0, 10);
            stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), 30L + randomInt, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 3、释放锁
            delLock(key);
        }
        return shop;
    }

    /**
     * 缓存击穿之逻辑过期
     * @param id
     * @return
     */
    private Shop LogicalExpire(Long id) {
        // 1、从redis中查询
        String shopKey = SHOP_KEY + id;
        String dataJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 2、缓存未命中返回空
        if (StrUtil.isBlank(dataJson)) {
            return null;
        }
        // 3、缓存命中，判断是否过期
        RedisData redisData = JSONUtil.toBean(dataJson, RedisData.class);
        LocalDateTime expire = redisData.getExpireTime();
        Shop data = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        if (expire.isAfter(LocalDateTime.now())) {
            // 3.1 未过期，返回店铺信息
            return data;
        }
        //4、过期，获取互斥锁
        String lockKey = "lock:shop:" + id;
        boolean lock = tryLock(lockKey);
        if (lock) {
            // 4.1 获取锁成功，开启独立线程
            // 判断缓存是否过期
            String dataJsonTemp = stringRedisTemplate.opsForValue().get(shopKey);
            RedisData redisDataTemp = JSONUtil.toBean(dataJsonTemp, RedisData.class);
            if (redisDataTemp.getExpireTime().isAfter(LocalDateTime.now())) {
                return JSONUtil.toBean((JSONObject) redisDataTemp.getData(), Shop.class);
            }
            // 重建缓存
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    saveShop2Redis(id, 30L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    delLock(lockKey);
                }
            });
        }
        // 5、返回数据
        return data;
    }
    @Override
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺不存在！");
        }
        // 1、先更新数据库
        updateById(shop);
        // 2、删除缓存
        stringRedisTemplate.delete(SHOP_KEY + id);
        return Result.ok();
    }

    /**
     * 获取互斥锁
     * @param key 锁的id
     * @return
     */
    private boolean tryLock(String key) {
        // 设置锁，过期时间10s
        Boolean absent = stringRedisTemplate.opsForValue()
                .setIfAbsent(key, "1", 10L, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(absent);
    }

    /**
     * 释放锁
     * @param key 锁的id
     */
    private void delLock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 数据预热
     * @param id 店铺id
     * @param expireTime 过期时间
     */
    public void saveShop2Redis(Long id, Long expireTime) {
        // 1、根据id查询数据库
        Shop shop = getById(id);
        // 2、封装数据RedisDate
        RedisData data = new RedisData();
        data.setData(shop);
        data.setExpireTime(LocalDateTime.now().plusMinutes(expireTime));
        // 3、保存到redis中
        stringRedisTemplate.opsForValue().set(SHOP_KEY + id, JSONUtil.toJsonStr(data));
    }
}
